From c9366090153e8aba3a673b2b77cbc8acc24e59a5 Mon Sep 17 00:00:00 2001
From: Rafi Zadanly <zadanlyr@gmail.com>
Date: Fri, 15 Dec 2023 17:15:32 +0700
Subject: Update promotion program feature

---
 src-migrate/pages/api/product-variant/[id].tsx | 45 ++++++++++++++++++++++++++
 1 file changed, 45 insertions(+)
 create mode 100644 src-migrate/pages/api/product-variant/[id].tsx

(limited to 'src-migrate/pages/api/product-variant/[id].tsx')

diff --git a/src-migrate/pages/api/product-variant/[id].tsx b/src-migrate/pages/api/product-variant/[id].tsx
new file mode 100644
index 00000000..ec95714d
--- /dev/null
+++ b/src-migrate/pages/api/product-variant/[id].tsx
@@ -0,0 +1,45 @@
+import { NextApiRequest, NextApiResponse } from "next";
+import { SolrResponse } from "~/common/types/solr";
+
+const SOLR_HOST = process.env.SOLR_HOST as string
+
+export default async function handler(req: NextApiRequest, res: NextApiResponse) {
+  const variantId = req.query.id as string
+  let price_tier = 'tier1'
+
+  let auth = req.cookies.auth ? JSON.parse(req.cookies.auth) : null
+  if (auth?.pricelist) price_tier = auth.pricelist
+
+  if (req.method === 'GET') {
+    const queryParams = new URLSearchParams({ q: `id:${variantId}` })
+    const response = await fetch(`${SOLR_HOST}/solr/variants/select?${queryParams.toString()}`)
+    const data: SolrResponse<any[]> = await response.json()
+
+    if (data.response.numFound === 0) {
+      res.status(404).json({ error: 'Variant not found' })
+      return
+    }
+
+    const variant = await extractVariant(data.response.docs[0], price_tier)
+
+    res.status(200).json({ data: variant })
+  }
+}
+
+const extractVariant = async (variant: any, price_tier: string) => {
+  const data: any = {}
+
+  data.id = parseInt(variant.id)
+  data.parent_id = variant.template_id_i
+  data.display_name = variant.display_name_s
+  data.image = variant.image_s
+  data.name = variant.name_s
+  data.default_code = variant.default_code_s
+  data.price = {
+    price: variant.price_v2_f,
+    discount_percentage: variant[`discount_${price_tier}_v2_f`] || 0,
+    price_discount: variant[`price_${price_tier}_v2_f`] || 0,
+  }
+
+  return data
+}
\ No newline at end of file
-- 
cgit v1.2.3

